import React, {createRef} from "react";
import {ReactComponent} from "../../class/ReactComponent";
import {TableBookList} from "../../../common/class/TableBookList";
import {Form, Modal} from "antd";
import {ArticleAddForm} from "../ArticleAddForm/ArticleAddForm";

export namespace ArticleAddPop {
    export type ModalCloseState = "okay" | "cancel";
    export interface Props extends ReactComponent.Props {
        showPop: boolean;
        onCloseModal: (modalState?: ModalCloseState, formData?: Partial<TableBookList.Data>) => void;
        formData?: Partial<TableBookList.Data>;
    }
    export interface State extends ReactComponent.State {}
}

export class ArticleAddPop extends ReactComponent<ArticleAddPop.Props, ArticleAddPop.State> {
    protected refForm = createRef<ArticleAddForm>();
    public render() {
        return (<Modal
            className={this.getClsName("article-add-pop-component")}
            visible={this.props.showPop}
            onCancel={this.onCloseModal.bind(this, "cancel")}
            onOk={this.onCloseModal.bind(this, "okay")}
            maskClosable={false}
        >{this.getFormElm()}</Modal>);
    }
    protected getFormElm() {
        const AddForm = Form.create<ArticleAddForm.Props>({})(ArticleAddForm);
        return (<AddForm initData={this.props.formData} wrappedComponentRef={this.refForm}/>);
    }
    protected onCloseModal(state: ArticleAddPop.ModalCloseState) {
        if (state === "okay") {
            const addForm = this.refForm.current;
            const antdForm = addForm.props.form;
            antdForm.validateFields((errors, values) => {
                if (!errors) {
                    this.props.onCloseModal(state, values);
                }
            });
        } else {
            this.props.onCloseModal(state);
        }
    }
}
